﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.Networking.Connectivity;


namespace DroneAPI
{
    class DroneConnection
    {
        private static DatagramSocket udpSocket;
        private static DataWriter udpWriter;

        // Initialize the connection to the drone
        public static async Task ConnectToDrone()
        {
            // Set up the UDP connection
            string remotePort = "5556";
            HostName droneIP = new HostName("192.168.1.1");

            udpSocket = new DatagramSocket();
            await udpSocket.BindServiceNameAsync(remotePort);
            await udpSocket.ConnectAsync(droneIP, remotePort);
            udpWriter = new DataWriter(udpSocket.OutputStream);
        }

        // Send a command to the drone
        public static async Task SendDroneCommand(string command)
        {
            udpWriter.WriteString(command);
            await udpWriter.StoreAsync();
        }

        // destroy the connection
        public static void CloseConnection()
        {
            udpSocket.Dispose();

            udpSocket = null;
            udpWriter = null;

            DroneControl.InterruptControlLoop();
        }

        // returns whether or not a connection exists
        public static bool ConnectionExists()
        {
            return udpSocket != null && udpWriter != null;
        }
    }
}
